import React, {Component} from 'react';
import {
    AsyncStorage,
    FlatList,
    Image,
    NativeModules,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    TextInput,
    TouchableOpacity,
    View,
} from 'react-native';
import Spinner from 'react-native-loading-spinner-overlay';
import Toast from '@remobile/react-native-toast';
import WebIM from './../../utils/Lib/WebIM';
import CountEmitter from './../../utils/event/CountEmitter';
import Swiper from 'react-native-swiper';
import {BasicStyle} from "../../../style/BasicStyle";
import {NavigationActions} from 'react-navigation';
import FetchUtils from './../../utils/FetchUtils'
import utils from './../../utils/utils';

export default class Index extends Component {

    constructor(props) {
        super(props);
        this._registerHXListener();
        this.state = {
            loadingStatus: false,
            swiperShow: false,
            flatListViewShow: false,
            page: 0,
            size: 5,
            article: {},
            articleLastStatus: false,
            banners: [],
            bannersView: [],
            userSuperView: [],
        };
    }

    /*在生命周期中请求数据*/
    componentDidMount() {
        if (Platform.OS === 'android') {
            NativeModules.Notification.showContentView();
        }

        AsyncStorage.getItem("XToken").then((xToken) => {
            AsyncStorage.getItem("HXToken").then((HXToken) => {
                AsyncStorage.getItem("username").then((username) => {
                    // this._loginToHXByToken(username, HXToken);
                    let param = {
                        XToken: xToken,
                    };
                    // console.log(HXToken);
                    if (HXToken != null) {
                        this._loginToHXByToken(username, HXToken);

                        FetchUtils.postWithParams(utils.apiUrl + '/user/validToken', JSON.stringify(param), (res) => {
                            // console.log(res);
                            if (res.code == 200) {
                                let params = {
                                    page: this.state.page,
                                    size: this.state.size,
                                };
                                FetchUtils.getWithHeader(utils.apiUrl + '/index', xToken, params, (res) => {
                                    /*生成banner图*/
                                    let bannersView = [];
                                    for (let n = 0; n < res.apiData.banners.length; n++) {
                                        bannersView.push(
                                            <Image key={res.apiData.banners[n].id}
                                                   source={{uri: utils.qiniuUrl + res.apiData.banners[n].resUrl}}
                                                   style={BasicStyle.bannerImg}/>
                                        );
                                    }
                                    /*生成精选搭配师*/
                                    let userSuperView = [];
                                    for (let n = 0; n < res.apiData.userSuper.length; n++) {
                                        let role = '';
                                        if (res.apiData.userSuper[n].role == 1) {
                                            role = '搭配师';
                                        } else if (res.apiData.userSuper[n].role == 2) {
                                            role = '体验官';
                                        }

                                        userSuperView.push(
                                            <TouchableOpacity key={res.apiData.userSuper[n].id}
                                                              style={styles.selecterBlock}
                                                              onPress={this.toProfileView.bind(this, res.apiData.userSuper[n].id, role)}>
                                                <Image
                                                    source={{uri: utils.qiniuUrl + res.apiData.userSuper[n].headerImg + utils.qiniu200Url}}
                                                    style={styles.selecterImg}/>
                                                <Text
                                                    style={styles.selecterName}>{res.apiData.userSuper[n].username}</Text>
                                            </TouchableOpacity>
                                        );
                                    }
                                    this.setState({
                                        banners: res.apiData.banners,
                                        bannersView: bannersView,
                                        userSuperView: userSuperView,
                                        article: res.apiData.article,
                                        articleLastStatus: res.apiData.article.last,
                                    });
                                    setTimeout(() => {
                                        this.setState({
                                            swiperShow: true
                                        });
                                    }, 0);
                                    setTimeout(() => {
                                        this.setState({
                                            flatListViewShow: true,
                                        })
                                    }, 0);

                                });

                            } else if (res.code == 500) {
                                const resetAction = NavigationActions.reset({
                                    index: 0,
                                    actions: [
                                        NavigationActions.navigate({routeName: 'RegisterLoginNav'})
                                    ]
                                });
                                this.props.navigation.dispatch(resetAction);
                            }
                        });
                    } else {
                        const resetAction = NavigationActions.reset({
                            index: 0,
                            actions: [
                                NavigationActions.navigate({routeName: 'RegisterLoginNav'})
                            ]
                        });
                        this.props.navigation.dispatch(resetAction);
                    }
                });

            });
        });

    }

    render() {
        /*轮播图,防止白图*/
        let mySwiper = this.state.swiperShow ?
            <Swiper horizontal={true} paginationStyle={{bottom: utils.autoWidth(10)}} showsButtons={false} autoplay={true}>
                {this.state.bannersView}
            </Swiper>
            :
            <Image source={require('./../../../img/banner_1.jpg')} style={BasicStyle.bannerImg}/>;

        /*FlatList组件*/
        let flstListView = this.state.flatListViewShow ?
            <FlatList
                data={this.state.article.content}
                renderItem={({item}) =>
                    this.getArticleItem(item)
                }
                keyExtractor={this._keyExtractor}
            />
            :
            null;
        return (
            <View style={styles.pageView}>
                <View style={styles.searchView}>
                    <TouchableOpacity onPress={this._searchInput.bind(this)}>
                        <TextInput style={styles.searchText} placeholder='搜索搭配师'
                                   underlineColorAndroid={'transparent'}
                                   editable={false}
                        ></TextInput>
                    </TouchableOpacity>
                </View>
                <Spinner visible={this.state.loadingStatus} textContent={""} textStyle={{color: '#FFF'}}/>
                <ScrollView
                    showsVerticalScrollIndicator={false}
                    showsHorizontalScrollIndicator={false}
                    removeClippedSubviews={false}
                    onMomentumScrollEnd={this._onScroll.bind(this)}
                >
                    <View style={BasicStyle.bannerView}>
                        {mySwiper}
                    </View>

                    <View style={styles.selecterView}>
                        <View style={styles.titleBlock}>
                            <View style={styles.blackBlock}></View>

                            <Text style={styles.selecterText}>精选搭配师</Text>
                        </View>

                        <View style={styles.selecterList}>
                            {this.state.userSuperView}
                        </View>
                    </View>

                    <View>
                        <View style={styles.titleBlock}>
                            <View style={styles.blackBlock}></View>

                            <Text style={styles.selecterText}>今日热门推荐</Text>
                        </View>

                        <View>
                            <View style={styles.hotList}>
                                {flstListView}
                            </View>

                        </View>
                    </View>

                    <Image style={BasicStyle.endImg} source={require('./../../../img/end.png')}/>

                </ScrollView>

            </View>
        );

    }

    // 注册环信的消息监听器
    _registerHXListener() {
        WebIM.conn.listen({
            // xmpp连接成功
            onOpened: (msg) => {
                if (msg.accessToken) {
                    AsyncStorage.setItem("HXToken", msg.accessToken, (error) => {
                        if (error) {
                            console.log("存值失败" + error)
                        } else {
                            console.log("存值成功");
                        }
                    })
                }
            },
            // 文本消息
            onTextMessage: (message) => {
                console.log(message);
                Toast.showShortTop(message.from + "，发来了一条消息");
                /*message.error
                * message.from
                * message.to
                * message.type*/
                this._converMSG(message);
                /*添加聊天列表记录*/
                this._addChatList(message.from)
            },
            // 各种异常
            onError: (error) => {
                Toast.showShortBottom(error.message);
            },
        });
    }

    /*收到消息添加聊天列表*/
    _addChatList = (fromName) => {
        AsyncStorage.getItem("XToken").then((xToken) => {
            let param = {
                toUser: {fromName: fromName},
            };
            FetchUtils.postWithParamHeader(utils.apiUrl + '/chat/list', param, xToken, (res) => {
                // console.log(res)
            });
        });
    };
    /*收到的消息转化存储*/
    _converMSG = (message) => {
        AsyncStorage.getItem("XToken").then((xToken) => {
            let param = {
                username: message.from
            };
            FetchUtils.getWithHeader(utils.apiUrl + '/user/userInfoByN', xToken, param, (res) => {
                if (res.code === 200) {
                    console.log(res);
                    AsyncStorage.getItem("userId").then((userId) => {
                        let fromMsg = [{
                            _id: message.id,//这个_id其实是这条消息的唯一标志
                            text: message.data,
                            createdAt: new Date().toDateString(),
                            user: {
                                _id: 2,//这里的_id=1是我发出的信息
                                name: message.from,
                                avatar: utils.qiniuUrl + res.apiData.headerImg + utils.qiniu200Url,
                            },
                        }];

                        AsyncStorage.getItem(userId + "_" + message.from + "_chatList").then((msg) => {
                            // console.log(msg)
                            if (msg === null) {
                                AsyncStorage.setItem(userId + "_" + message.from + "_chatList", JSON.stringify(fromMsg), (error) => {
                                    if (error) {
                                        console.log(error)
                                    } else {
                                        CountEmitter.emit("ChatRefresh")
                                    }
                                });
                            } else {
                                let jsonMsg = JSON.parse(msg);
                                let newMsg = fromMsg.concat(jsonMsg);
                                console.log(newMsg);
                                AsyncStorage.setItem(userId + "_" + message.from + "_chatList", JSON.stringify(newMsg), (error) => {
                                    console.log(error);
                                    if (error) {
                                        console.log(error)
                                    } else {
                                        CountEmitter.emit("ChatRefresh")
                                    }
                                });
                            }
                        })
                    })
                } else {
                    console.log(res.apiData);
                }
            })
        })
    };
    /*前往详情页*/
    toProfileView = (id, role) => {
        let {navigate} = this.props.navigation;
        navigate('StyleManProfileNav', {userId: id, role: role})
    };
    /*返回文章列表*/
    getArticleItem = (item) => {
        return(
            <TouchableOpacity onPress={this.toArticleView.bind(this,item.id)}>
                <Image style={styles.hotListItem}
                       source={{uri: utils.qiniuUrl + item.mainImg + utils.qiniu200Url}}>
                    <View style={styles.hotListItemTextView}>
                        <Text style={styles.hotListItemTextUp}>{item.mainTitle}</Text>
                        <View style={styles.hotListItemline}/>
                        <Text style={styles.hotListItemTextBottom}>{item.title}</Text>
                    </View>
                </Image>
            </TouchableOpacity>
        )
    };
    /*前往文章详情页*/
    toArticleView = (id) => {
        console.log(id);
        let {navigate} = this.props.navigation;
        navigate('IndexArticleNav', {articleId: id})
    };
    // 登录环信聊天服务器
    _loginToHXByToken = (username, HXToken) => {
        if (WebIM.conn.isOpened()) {
            WebIM.conn.close('logout');
        }
        // console.log(HXToken);
        // 下面调用成功后，会回调SplashScreen中注册的listener
        WebIM.conn.open({
            apiUrl: WebIM.config.apiURL,
            user: username,
            accessToken: HXToken,
            appKey: WebIM.config.appkey,
        });
    };
    /*生成列表key*/
    _keyExtractor = (item, index) => item.id;
    /*搜索框*/
    _searchInput = () => {
        let {navigate} = this.props.navigation;
        navigate('SearchPageNav')
    };

    /*scrollView滑动方法*/
    _onScroll(event) {
        let y = event.nativeEvent.contentOffset.y;//滑动距离
        let height = event.nativeEvent.layoutMeasurement.height;//scrollView高度
        let contentHeight = event.nativeEvent.contentSize.height;//scrollView contentSize高度
        if (y + height >= contentHeight) {
            AsyncStorage.getItem("XToken").then((xToken) => {
                if (!this.state.articleLastStatus) {
                    this.setState({loadingStatus: true});
                    let params = {page: this.state.page + 1, size: this.state.size,};
                    FetchUtils.getWithHeader(utils.apiUrl + '/index/artPage', xToken, params, (res) => {
                        if (res.code == 200) {
                            let oldArtContent = this.state.article.content;
                            let articleContent = res.apiData.article.content;
                            let newArt = {
                                first: res.apiData.article.first,
                                last: res.apiData.article.last,
                                number: res.apiData.article.number,
                                numberOfElements: res.apiData.article.numberOfElements,
                                size: res.apiData.article.size,
                                sort: res.apiData.article.sort,
                                totalElements: res.apiData.article.totalElements,
                                totalPages: res.apiData.article.totalPages,
                                content: oldArtContent.concat(articleContent),

                            };
                            this.setState({
                                article: newArt,
                                articleLastStatus: res.apiData.article.last,
                                page: res.apiData.article.number,
                                size: res.apiData.article.size,
                                loadingStatus: false,
                            });
                        }
                    })
                }
            });
        } else {
            this.setState({loadingStatus: false})
        }
    }
}
;

const styles = StyleSheet.create({
    pageView: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'flex-start',
        backgroundColor: '#FFFFFF',
    },
    searchView: {
        height: utils.autoheight(44),
        backgroundColor: '#FAFAFA',
        alignItems: 'center',
        flexDirection: 'column',
        justifyContent: 'center',
    },
    searchText: {
        height: utils.autoheight(28),
        backgroundColor: '#DEDEDE',
        borderRadius: 5,
        width: utils.autoWidth(359),
        fontSize: utils.setSpText(14),
        lineHeight: utils.autoheight(28),
        paddingTop: 0,
        paddingBottom: 0,
        fontFamily: '.SFNSText',
        textAlign: 'center'
    },
    selecterView: {
        height: utils.autoheight(130),
        marginTop: utils.autoheight(5),
    },
    titleBlock: {
        flexDirection: 'row',
    },
    blackBlock: {
        backgroundColor: '#010101',
        width: utils.autoWidth(7),
        height: utils.autoheight(25),
    },
    selecterText: {
        marginLeft: utils.autoWidth(7.5),
        fontSize: utils.setSpText(15),
        color: '#010101',
    },
    selecterBlock: {
        alignItems: 'center',
    },
    selecterList: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        height: utils.autoheight(109),
        marginTop: utils.autoheight(13),
    },
    selecterImg: {
        height: utils.autoWidth(55),
        width: utils.autoWidth(55),
        borderRadius: utils.autoWidth(27.5),
    },
    selecterName: {
        fontSize: utils.setSpText(15),
        color: '#000000',
    },
    hotList: {
        alignItems: 'center',
    },
    hotListItem: {
        marginTop: utils.autoheight(10),
        height: utils.autoheight(197.2),
        width: utils.autoWidth(355),
        justifyContent: 'flex-end',

    },
    hotListItemTextView: {
        height: utils.autoheight(60),
        backgroundColor: 'rgba(246,246,246,0.80)',
        paddingLeft: utils.autoWidth(10),
    },
    hotListItemTextUp: {
        marginTop: utils.autoheight(5),
        fontSize: utils.setSpText(17),
        color: '#000000',
        marginBottom: utils.autoheight(2),
    },
    hotListItemline: {
        width: utils.autoWidth(25),
        height: utils.autoheight(2),
        backgroundColor: '#4A4A4A',
    },
    hotListItemTextBottom: {
        marginTop: utils.autoheight(3),
        fontSize: utils.setSpText(15),
        color: '#000000',
        fontFamily: 'PingFangSC-Light',
    },
});